package com.demo.delivery.data;

import android.content.res.AssetManager;
import android.text.TextUtils;

import com.demo.delivery.entity.Food;
import com.demo.delivery.entity.Store;
import com.demo.delivery.utils.AppUtils;
import com.demo.delivery.utils.JsonUtils;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class DataContent {

    /**
     * 使用gson从assets中读取store.json的数据
     * 获取商店列表
     */
    public static List<Store> getStoreList(String name) {
        //读取assets中的store.json文件
        String json = getJson("store.json");
        //将json转换为List<Store>
        List<Store> storeList = JsonUtils.parse(json, new TypeToken<List<Store>>() {
        });
        //筛选包含name的商店
        if (storeList != null && !TextUtils.isEmpty(name)) {
            for (int i = 0; i < storeList.size(); i++) {
                if (!storeList.get(i).getName().contains(name)) {
                    storeList.remove(i);
                    i--;
                }
            }
        }
        //随机打乱顺序
        if (storeList != null) {
            for (int i = 0; i < storeList.size(); i++) {
                int randomIndex = (int) (Math.random() * storeList.size());
                Store temp = storeList.get(i);
                storeList.set(i, storeList.get(randomIndex));
                storeList.set(randomIndex, temp);
            }
        }
        return storeList;
    }

    /**
     * 获取食物列表
     */
    public static List<Food> getFoodList() {
        String json = getJson("food.json");
        List<Food> foodList = JsonUtils.parse(json, new TypeToken<List<Food>>() {
        });
        //随机打乱顺序
        if (foodList != null) {
            for (int i = 0; i < foodList.size(); i++) {
                int randomIndex = (int) (Math.random() * foodList.size());
                Food temp = foodList.get(i);
                foodList.set(i, foodList.get(randomIndex));
                foodList.set(randomIndex, temp);
            }
        }
        return foodList;
    }

    private static String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = AppUtils.getApplication().getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));

            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException var6) {
            var6.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
